import { createTeam } from "@/api/team/add"
import { selectUserDetail } from "@/lib/features/login/loginSlice"
import { setTeamData } from "@/lib/features/team/teamSlice"
import { useAppDispatch, useAppSelector } from "@/lib/hooks"
import { getRandomEmojiTeam, unicodeToEmoji } from "@/utils/randomemoji"
import { Button, Input, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader } from "@nextui-org/react"
import { useState } from "react"
import toast from "react-hot-toast"


const AddTeam = ({ isOpen, onClose }: { isOpen: boolean, onClose: () => void }) => {

    const [iconValue, setIconValue] = useState<number>(0x1F680)
    const [teamName, changeTeamName] = useState<string>("")

    const { email } = useAppSelector(selectUserDetail)
    const dispatch = useAppDispatch()

    const resetState = () => {
        setIconValue(0x1F680)
        changeTeamName("")
        onClose()
    }

    const addTeam = async () => {
        const result = await createTeam({ email, team_name: teamName, emoji: iconValue })
        toast.dismiss()
        if (result.code == 200) {
            dispatch(setTeamData({ user_id: result.data.user_id, team_name: teamName, emoji: iconValue }))
            
            toast.success(result.message)
        } else {
            toast.error(result.message)
        }
        // 刷新视图
        resetState()
        
    }

    return (
        <>
            <Modal backdrop={"blur"} isDismissable={false} isOpen={isOpen} onClose={onClose} scrollBehavior="inside" placement="center">
                <ModalContent>
                    <>
                        <ModalHeader className="flex flex-row items-center gap-1">
                            <Button isIconOnly className="mr-1" color="secondary" size="md" radius="md" onPress={() => setIconValue(getRandomEmojiTeam())}><span className="text-3xl">{unicodeToEmoji(iconValue)}</span></Button>
                            <span className="text-white">Create your Team ✨</span>
                        </ModalHeader>
                        <ModalBody>
                            <Input label={<span className="text-white font-bold text-[16px]">Team name</span>} onValueChange={(v: string) => changeTeamName(v)} value={teamName} defaultValue={teamName} size="sm" type="text" variant="underlined" />
                        </ModalBody>
                        <ModalFooter>
                            <Button color="danger" variant="light" onPress={() => onClose()}>
                                Cancel
                            </Button>
                            <Button color="primary" onPress={() => addTeam()}>
                                Add
                            </Button>
                        </ModalFooter>
                    </>
                </ModalContent>
            </Modal>
        </>
    )
}

export default AddTeam